package com.apex.sdk.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.apex.bluetooth.callback.TitanActivityCountCallback;
import com.apex.bluetooth.callback.TitanBodyTempCountCallback;
import com.apex.bluetooth.callback.TitanHeartRateCountCallback;
import com.apex.bluetooth.callback.TitanMultiCountCallback;
import com.apex.bluetooth.callback.TitanSleepCountCallback;
import com.apex.bluetooth.callback.TitanSpo2CountCallback;
import com.apex.bluetooth.callback.TitanStressCountCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.model.TitanDataSyncType;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityAddAlarmBinding;
import com.apex.sdk.databinding.ActivityTitanSyncDataBinding;
import com.apex.sdk.dialog.PriorityDialog;
import com.apex.sdk.dialog.WaitingDialog;

public class TitanSyncData extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();

    private WaitingDialog waitingDialog;
    private PriorityDialog priorityDialog;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
            } else if (msg.what == 0x41) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(TitanSyncData.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
            }
        }
    };
    final String TitanDataSync = "com.titan.data.sync.count";
    final String SyncResult = "com.titan.data.sync.result";
    private TitanDataSyncResultBroadcast titanDataSyncResultBroadcast;
    ActivityTitanSyncDataBinding activityTitanSyncDataBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityTitanSyncDataBinding=ActivityTitanSyncDataBinding.inflate(getLayoutInflater());
        setContentView(activityTitanSyncDataBinding.getRoot());
        activityTitanSyncDataBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityTitanSyncDataBinding.tool);
        getSupportActionBar().setTitle(null);
        activityTitanSyncDataBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titanDataSyncResultBroadcast = new TitanDataSyncResultBroadcast();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            registerReceiver(titanDataSyncResultBroadcast, new IntentFilter(SyncResult),Context.RECEIVER_EXPORTED);
        }else {
            registerReceiver(titanDataSyncResultBroadcast, new IntentFilter(SyncResult));
        }
        activityTitanSyncDataBinding.dataType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_CONNECTED) {
                    if (priorityDialog == null) {
                        priorityDialog = new PriorityDialog(TitanSyncData.this);
                        priorityDialog.setSelectListener(new PriorityDialog.SelectListener() {
                            @Override
                            public void selectData(String sex) {
                                activityTitanSyncDataBinding.dataType.setText(sex);
                                if (waitingDialog == null) {
                                    waitingDialog = new WaitingDialog(TitanSyncData.this);
                                }
                                waitingDialog.show();

                                if (sex.equalsIgnoreCase(getString(R.string.priority_sync_daily))) {
                                    EABleManager.getInstance().syncTitanDailySportData(TitanDataSyncType.BEGIN, new TitanActivityCountCallback() {

                                        @Override
                                        public void activityCount(int activityCount) {
                                            if (activityCount <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 0);
                                                intent.putExtra("totalCount", activityCount);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }

                                        }
                                    });

                                } else if (sex.equalsIgnoreCase(getString(R.string.priority_sync_sleep))) {
                                    EABleManager.getInstance().syncTitanSleepData(TitanDataSyncType.BEGIN, new TitanSleepCountCallback() {
                                        @Override
                                        public void sleepCount(int count) {
                                            if (count <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 1);
                                                intent.putExtra("totalCount", count);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }
                                        }
                                    });

                                } else if (sex.equalsIgnoreCase(getString(R.string.priority_sync_heart_rate))) {
                                    EABleManager.getInstance().syncTitanHeartRateData(TitanDataSyncType.BEGIN, new TitanHeartRateCountCallback() {
                                        @Override
                                        public void heartCount(int count) {
                                            if (count <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 2);
                                                intent.putExtra("totalCount", count);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }
                                        }
                                    });

                                } else if (sex.equalsIgnoreCase(getString(R.string.priority_sync_multi))) {
                                    EABleManager.getInstance().syncTitanMultiData(TitanDataSyncType.BEGIN, new TitanMultiCountCallback() {
                                        @Override
                                        public void multiCount(int count) {
                                            if (count <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 3);
                                                intent.putExtra("totalCount", count);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }
                                        }
                                    });

                                } else if (sex.equalsIgnoreCase(getString(R.string.priority_sync_stress))) {
                                    EABleManager.getInstance().syncTitanStressData(TitanDataSyncType.BEGIN, new TitanStressCountCallback() {
                                        @Override
                                        public void stressCount(int count) {
                                            if (count <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 5);
                                                intent.putExtra("totalCount", count);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }
                                        }
                                    });

                                } else if (sex.equalsIgnoreCase(getString(R.string.priority_sync_blood))) {
                                    EABleManager.getInstance().syncTitanSpo2Data(TitanDataSyncType.BEGIN, new TitanSpo2CountCallback() {
                                        @Override
                                        public void spo2Count(int count) {
                                            if (count <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 4);
                                                intent.putExtra("totalCount", count);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }
                                        }
                                    });

                                } else if (sex.equalsIgnoreCase(getString(R.string.body_temp))) {
                                    EABleManager.getInstance().syncTitanBodyTemperatureData(TitanDataSyncType.BEGIN, new TitanBodyTempCountCallback() {
                                        @Override
                                        public void tempCount(int count) {
                                            if (count <= 0) {
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x40);
                                                }
                                            } else {
                                                Intent intent = new Intent(TitanDataSync);
                                                intent.putExtra("type", 6);
                                                intent.putExtra("totalCount", count);
                                                sendBroadcast(intent);
                                            }

                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x41);
                                            }
                                        }
                                    });

                                }

                            }
                        });
                    }
                    if (!priorityDialog.isShowing()) {
                        priorityDialog.show();
                    }
                }
            }
        });
    }

    class TitanDataSyncResultBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action) && action.equalsIgnoreCase(SyncResult)) {
                int resutlt = intent.getIntExtra("result", 0);
                String sportIds = intent.getStringExtra("idList");

                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                if (resutlt != 0) {
                    Log.e(TAG, "同步数据失败");
                    Toast.makeText(TitanSyncData.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
                } else {
                    if (!TextUtils.isEmpty(sportIds) && !"".equalsIgnoreCase(sportIds)) {
                        Intent intent1 = new Intent(TitanSyncData.this, TitanSportDetailActivity.class);
                        intent1.putExtra("data", sportIds);
                        startActivity(intent1);
                    }
                }

            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        if (titanDataSyncResultBroadcast != null) {
            unregisterReceiver(titanDataSyncResultBroadcast);
            titanDataSyncResultBroadcast = null;
        }
        super.onDestroy();
    }
}
